import optparse
import sys

import tables

from charmicat import BadCommandLineError

def main():
    '''
    python -m batchcat.run.indices input_file col1 [col2 [...]]

    Batch-processing module for `bcat_indices.py'
    '''

    op = optparse.OptionParser()

    opts, args = op.parse_args()

    try:
        input_file = args.pop(0)
    except IndexError:
        msg = "Please supply an input file and at least one column name to generate an index for."
        raise BadCommandLineError(msg, -1)

    if len(args) == 0:
        msg = "Please supply at least one column name to generate an index for."
        raise BadCommandLineError(msg, -2)
        
    with tables.openFile(input_file, 'r+') as fp:
        for col in args:
            if fp.root.nt.colindexed[col]:
                continue

            fp.root.nt.colinstances[col].createIndex()


    
if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)

